package com.zl.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zl.common.thread.TokenThread;
import com.zl.entity.BrowseRecord;
import com.zl.entity.Member;
import com.zl.entity.NewsEntity;
import com.zl.entity.QueryEntity;
import com.zl.entity.Role;
import com.zl.entity.SubscribeEntity;
import com.zl.service.BorwseService;
import com.zl.service.CollectService;
import com.zl.service.MemberService;
import com.zl.service.RoleService;
import com.zl.service.SubscribeService;
import com.zl.service.UserService;
import com.zl.util.JsonMapper;
import com.zl.util.SearchUtils;
import com.zl.weixin.entity.AccessToken;
import com.zl.weixin.entity.UserClient;
import com.zl.weixin.util.WeixinUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**   
* @Title: CenterController.java 
* @Package com.zl.controller 
* @Description: 我的中心控制类
* @author chxl   
* @date 2015年8月12日 上午10:53:22 
* @version V1.0   
*/
@Controller
@RequestMapping("center")
@Scope("prototype")
public class CenterController {
	Logger log = LoggerFactory.getLogger(CenterController.class);
	@Autowired
	private MemberService memberService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private CollectService collectService;
	@Autowired
	private BorwseService borwseService;
	@Autowired
	private SubscribeService subscribeService;
	@Autowired
	private UserService userService;
	
	@RequestMapping("index")
	public String index(Model model,HttpServletRequest request){
		String code = request.getParameter("code");//通过微信回调得到的参数
		log.info("========code========");
		log.info(code);
		log.info("========code end========");
		String appId = "wxac9a290c5dc49ed0";
    	// 第三方用户唯一凭证密钥
    	String appSecret = "24dd8e15cfeb82fc1c0ac60c8705d75c";
    	UserClient user = new UserClient();
    	if(StringUtils.isNotBlank(code)){
    		String openId = WeixinUtil.getOpenId(appId, appSecret, code).getOpenid();//通过code调取openid
    		log.info("========openid========");
    		log.info(openId);
    		log.info("========openid end========");
    		AccessToken at = TokenThread.accessToken;
    		log.info("========token========");
    		log.info(at.getToken());
    		log.info("========token end========");
        	if(at!=null){
        		if(request.getSession().getAttribute("user")==null){
        			if(StringUtils.isBlank(openId)){
        				return "";
        			}
        			user= WeixinUtil.getUser(at.getToken(), openId);
	        		request.getSession().setAttribute("user", user); //将对象放入session中
	    		}else{
	    			user = (UserClient)request.getSession().getAttribute("user");
	    		}//将对象放入session中
        		
        	}else{
        		TokenThread.accessToken = WeixinUtil.getAccessToken(appId, appSecret); 
        		at = TokenThread.accessToken;
        		if(request.getSession().getAttribute("user")==null){
        			if(StringUtils.isBlank(openId)){
        				return "";
        			}
        			user= WeixinUtil.getUser(at.getToken(), openId);
	        		request.getSession().setAttribute("user", user); //将对象放入session中
	    		}else{
	    			user = (UserClient)request.getSession().getAttribute("user");
	    		}
        	}
    	}else{
//    		user.setOpenid("oFOgks6AbGnBns_u2teOtiMG712c");
//    		user.setNickname("我是兔八哥");
    		//model.addAttribute("user", user);
//    		userService.register(user);
//    		request.getSession().setAttribute("user", userClient);
			user = (UserClient)request.getSession().getAttribute("user");
    	}
		//UserClient userClient = new UserClient();
//		userClient.setOpenid("oFOgks6AbGnBns_u2teOtiMG711c");
//		userClient.setNickname("我是兔八哥");
		model.addAttribute("user", user);
//		request.getSession().setAttribute("user", userClient);
		if(user==null){
			return "";//转跳未获取用户信息页面
		}
		String id = user.getOpenid();
		
		List<NewsEntity> newslist = collectService.getCollectNews(id);
		model.addAttribute("collectCount", newslist.size());
		List<BrowseRecord> borwselist = borwseService.getBrowseByUser(id);
		model.addAttribute("browseCount", borwselist.size());
		
		Member member = memberService.getMemberByOpenId(id);
		model.addAttribute("member", member);
		
		Date memberDueDate = member.getMemberDueTime();//会员到期日
		long timeInterval = (memberDueDate.getTime()-(new Date()).getTime());
		int memberDay = (int) (timeInterval/(24 * 60 * 60 * 1000));
		
		Role role = member.getRole();
		boolean isMinGrade = roleService.isMinGrade(role);
		boolean isMaxGrade = roleService.isMaxGrade(role);
		boolean isGroup = roleService.isGroup(role);
		
		model.addAttribute("isMinGrade",isMinGrade);
		model.addAttribute("isMaxGrade",isMaxGrade);
		model.addAttribute("isGroup",isGroup);
		model.addAttribute("memberDay",memberDay);
		return "uc_home";
	}
	
	@RequestMapping("userinfo")
	public String userinfo(Model model,HttpServletRequest request){
		UserClient userClient = (UserClient)request.getSession().getAttribute("user");
		model.addAttribute("user", userClient);
		Member member = memberService.getMemberByOpenId(userClient.getOpenid());
		model.addAttribute("member", member);
		return "uc_uinfo";
	}
	
	/**
	 *  推送设置
	 * @return
	 */
	@RequestMapping("pushSetting")
	public String pushSettingIndex(Model model,HttpServletRequest request){
		UserClient user = (UserClient)request.getSession().getAttribute("user");
//		UserClient user = new UserClient();
//		user.setOpenid("oFOgks6AbGnBns_u2teOtiMG711c");
		Member member = memberService.getMemberByOpenId(user.getOpenid());
		model.addAttribute("ispush", member.getIsPush());
		return "uc_ps";
	}
	
	/**
	 * 推送设置保存
	 * @return
	 */
	@RequestMapping("pushSave")
	@ResponseBody
	public String pushSettingSave(HttpServletRequest request){
		String status = request.getParameter("status");
//		UserClient user = new UserClient();
//		user.setOpenid("oFOgks6AbGnBns_u2teOtiMG711c");
		UserClient user = (UserClient)request.getSession().getAttribute("user");

		Member member = new Member();
		member.setOpenId(user.getOpenid());
		member.setIsPush(status);
		
		Map<String,String> result = new HashMap<String,String>();
		memberService.updatePushStatus(member);
		result.put("msg", "保存成功");
		result.put("type", "1");
		return JsonMapper.nonDefaultMapper().toJson(result);
	}
	
	@RequestMapping("aboutUs")
	public String aboutUs(){
		return "uc_about";
	}
	
	/**
	 * 用户信息修改
	 * @return
	 */
	@RequestMapping("userModify")
	public String userModify(Model model,HttpServletRequest request){
		String type = request.getParameter("type");
		String typeText = "请填写真实的";
		if("telephone".equals(type)){
			typeText = typeText+"电话号码";
		}else if("company".equals(type)){
			typeText = typeText+"公司名称";
		}else if("address".equals(type)){
			typeText = typeText+"住址信息";
		}else{
			typeText = typeText+"信息";
		}
		model.addAttribute("type", type);
		model.addAttribute("typeText", typeText);
		return "uc_uinfo_modify";
	}
	
	/**
	 * @return
	 */
	@RequestMapping("userSave")
	@ResponseBody
	public String userSave(HttpServletRequest request){
		UserClient user = (UserClient)request.getSession().getAttribute("user");
//		UserClient user = new UserClient();
//		user.setOpenid("oFOgks6AbGnBns_u2teOtiMG711c");
		Map<String,String> result = new HashMap<String,String>();
		
		String type = request.getParameter("type");
		String keyword = request.getParameter("key");
		Map<String,String> param = new HashMap<String,String>();
		param.put("openid", user.getOpenid());
		if("telephone".equals(type)){
			if(!isMobileNO(keyword)){
				result.put("type", "0");
				result.put("msg", "手机号码不符合");
				return JsonMapper.nonDefaultMapper().toJson(result);
			}
			param.put("type", "lxrsjhm");
		}else if("company".equals(type)){
			param.put("type", "dwmc");
		}else if("address".equals(type)){
			param.put("type", "job");
		}
		param.put("key", keyword);
		memberService.updateMemberValue(param);
		result.put("type", "1");
		result.put("msg", "保存成功");
		return JsonMapper.nonDefaultMapper().toJson(result);
	}
	
	public static boolean isMobileNO(String mobiles){
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9])|(17[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();

	}
	
}
